package com.hxk.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.hxk.pojo.User;
import com.hxk.service.UserServie;

@Service
public class UserServiceImpl implements UserServie {

	@Autowired
	private LoadBalancerClient loadBalancerClient;//ribbon 负载均衡器
	
	@Override
	public List<User> getUsers() {
		//选择调用的服务的名称
		//ServiceInstance 封装了服务的基本信息，如 IP，端口
		ServiceInstance si = loadBalancerClient.choose("eureka-provider");
		StringBuffer url = new StringBuffer("http://");
		url.append(si.getHost()).append(":").append(si.getPort()).append("/users");
		//springMVC RestTemplate
		RestTemplate rt = new RestTemplate();
		//设置返回值类型
		ParameterizedTypeReference<List<User>> responseType = new ParameterizedTypeReference<List<User>>() {};
		//发送http请求调用另一个服务地址获取数据
		ResponseEntity<List<User>> exchange = rt.exchange(url.toString(), HttpMethod.GET, null, responseType);
		return exchange.getBody();
	}

}
